package com.chenjiahao.kaiyanwan.ui.hot

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.chenjiahao.kaiyanwan.R
import com.chenjiahao.kaiyanwan.base.BaseFragment
import com.chenjiahao.kaiyanwan.base.BaseFragmentAdapter
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle
import com.chenjiahao.kaiyanwan.logic.util.StatusBarUtil
import kotlinx.android.synthetic.main.fragment_hot.*
import java.lang.Exception

class HotFragment : BaseFragment() {
    override fun getLayoutId(): Int = R.layout.fragment_hot
    private var mTitle: String? = null

    private val viewModel by lazy { ViewModelProvider(this).get(HotTabViewModel::class.java) }

    companion object {
        fun getInstance(title: String): HotFragment {
            val fragment = HotFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    override fun initView() {
        mLayoutStatusView = multipleStatusView
        //状态栏透明和间距处理
        activity?.let { StatusBarUtil.darkMode(it) }
        activity?.let { StatusBarUtil.setPaddingSmart(it, toolbar) }
    }

    private fun showLoading() {
        multipleStatusView.showLoading()
    }

    private fun dismissLoading() {
        multipleStatusView.showContent()
    }

    override fun lazyLoad() {
        viewModel.requestRankListLiveData()
        showLoading()
        viewModel.RankListData.observe(this, Observer {
            val rankListData=it.getOrNull()
            dismissLoading()
            if(rankListData!=null){
                rankListData.tabInfo.tabList.mapTo(viewModel.mTabTitleList) { it.name }
                rankListData.tabInfo.tabList.mapTo(viewModel.mFragmentList) {
                    RankFragment.getInstance(it.apiUrl) }
                mViewPager.adapter = BaseFragmentAdapter(childFragmentManager,viewModel.mFragmentList,viewModel.mTabTitleList)
                mTabLayout.setupWithViewPager(mViewPager)
            }else{
                showError(ExceptionHandle.handleException(it.exceptionOrNull() as Exception), ExceptionHandle.errorCode)
            }
        })
    }
}